package com.dream.auth.config.security.handle;

import com.alibaba.fastjson.JSON;
import com.dream.auth.domain.models.LoginUser;
import com.dream.auth.web.service.TokenService;
import com.dream.core.config.DreamAppConfig;
import com.dream.core.constant.Constants;
import com.dream.core.core.domain.AjaxResult;
import com.dream.web.utils.ServletUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandlerImpl extends SavedRequestAwareAuthenticationSuccessHandler {

    protected final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    private TokenService tokenService;

    @Autowired
    DreamAppConfig dreamAppConfig;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        if(!dreamAppConfig.getSeparate()){
            super.onAuthenticationSuccess(request, response, authentication);
        }else{
            AjaxResult ajax = AjaxResult.success();
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            // 生成token
            String token = tokenService.createToken(loginUser);
            ajax.put(Constants.TOKEN, token);
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success("登录成功").put(Constants.TOKEN, token)));
        }
    }
}